package com.dragon.framework.filter;

import com.dragon.common.constant.BasicConstant;
import com.dragon.common.utils.MdcUtils;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 全局追踪ID过滤器
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/15 17:16
 */
@Slf4j
@Component
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

            String traceId = httpServletRequest.getHeader(BasicConstant.HEADER_TRACE_ID);
            if (StringUtils.isBlank(traceId)) {
                traceId = MdcUtils.safeGenerate(BasicConstant.TRACE_ID);
            }

            // 设置追踪ID
            MdcUtils.put(BasicConstant.TRACE_ID, traceId);
            // 设置响应头
            httpServletResponse.setHeader(BasicConstant.HEADER_TRACE_ID, traceId);

        } catch (Exception e) {
            log.error("全局追踪ID过滤器异常", e);
        }

        filterChain.doFilter(servletRequest, servletResponse);

        MdcUtils.remove(BasicConstant.TRACE_ID);
    }

    @Override
    public void destroy() {
        MdcUtils.remove(BasicConstant.TRACE_ID);
    }

}
